package com.aoyama.juc._05_lock;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author ：qs
 * @date ：Created in 2022/7/18
 * @description：ReentrantReadWriteLock 悲观锁
 * @modified By：
 */
public class Lock01 {

    private static final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();

    private static final Lock readLock = lock.readLock();
    private static final Lock writeLock = lock.writeLock();

    private static final List<String> data = new ArrayList<>();

    public static void main(String[] args) throws InterruptedException {
        new Thread(()->write(),"write-1").start();

        Thread.sleep(1000);
        new Thread(()->read(),"read-1").start();

        new Thread(()->read(),"read-2").start();

    }

    public static void write(){
        try{
            writeLock.lock();
            data.add("数据XXX");
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            System.out.println("写锁释放");
            writeLock.unlock();
        }
    }

    public static void read(){
        try{
            readLock.lock();
            for (String datum : data) {
                System.out.println(Thread.currentThread().getName() + " 读入："+datum);
            }
            Thread.sleep(3000);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            System.out.println("读锁释放");
            readLock.unlock();
        }
    }

}
